package com.link.init;

import com.link.util.SpringUtil;
import com.netflix.appinfo.ApplicationInfoManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 应用启动后生成一个文件，存储应用状态信息，便于脚本检查
 * @author 郭闪
 * @date 2019/12/11
 */
@Component
public class IniCommand implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(IniCommand.class);

    /**
     * 应用启动完成后会执行此方法，在方法中生成文件，存储应用启动状态
     * @author 郭闪
     * @date 2019/12/11
     * @param args  系统启动参数
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {

        ApplicationInfoManager infoManager = SpringUtil.getBean(ApplicationInfoManager.class);
        String name = infoManager.getInfo().getStatus().name();
        Path fpath = Paths.get("status.txt");
        //创建文件
        if (!Files.exists(fpath)) {
            try {
                Files.createFile(fpath);
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        //创建BufferedWriter
        BufferedWriter bfw = null;
        try {
            bfw = Files.newBufferedWriter(fpath);
            bfw.write(name);
            bfw.flush();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (bfw != null) {
                try {
                    bfw.close();
                } catch (IOException io) {
                    logger.error(io.getMessage());
                }
            }
        }
    }
}
